/**
 * 根据类型创建画笔
 * @param {object} source 数据源对象
 * @param {string} type 画笔的类型['Point', 'LineString', 'Circle', 'Square', 'Box']
 * @param {function} callback2 (可选) 绘制开始的回调函数
 * @param {function} callback1 (可选) 绘制结束时的回调
 * @returns {Ol.interaction.Draw} draw
 */
function createDraw(source, type, callback1, callback2) {
  let geometryFunction = null
  let maxPoints = 0

  const support = ['Point', 'LineString', 'Circle', 'Polygon', 'Square', 'Box']

  if (!support.includes(type)) {
    type = 'Point'
  }

  if (type == 'Square') {
    type = 'Circle'
    geometryFunction = ol.interaction.Draw.createRegularPolygon(4)
  } else if (type == 'Box') {
    type = 'LineString'
    geometryFunction = function (coordinates, geometry) {
      if (!geometry) {
        //多边形
        geometry = new ol.geom.Polygon(null)
      }
      const start = coordinates[0] // 绘制的第一个点的坐标
      const end = coordinates[1] // 绘制的第二个点的坐标
      geometry.setCoordinates([
        [start, [start[0], end[1]], end, [end[0], start[1]], start],
      ])
      return geometry
    }
    maxPoints = 2
  }
  const draw = new ol.interaction.Draw({
    source,
    type,
    geometryFunction,
    maxPoints,
    style: new ol.style.Style({
      //绘制几何图形的样式
      fill: new ol.style.Fill({
        color: 'rgba(255, 255, 255, 0.5)',
      }),
      stroke: new ol.style.Stroke({
        color: 'rgba(0, 0, 0, 0.5)',
        lineDash: [10, 10],
        width: 2,
      }),
      image: new ol.style.Circle({
        radius: 5,
        stroke: new ol.style.Stroke({
          color: 'rgba(0, 0, 0, 0.7)',
        }),
        fill: new ol.style.Fill({
          color: 'rgba(255, 255, 255, 0.2)',
        }),
      }),
    }),
  })

  // if (callback) {
  //   draw.on('drawend', callback)
  // }
  callback2 && draw.on('drawstart', callback2, this)
  callback1 && draw.on('drawend', callback1, this)

  return draw
}
